package com.guldan.thrall.common.filter;

import com.guldan.core.dubbo.client.ResponseDTO;
import com.guldan.core.response.ResponseJsonBean;
import com.guldan.jaina.dto.users.UserCacheDTO;
import com.guldan.jaina.provider.IAuthorityProvider;
import com.guldan.thrall.util.UserUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * Created by Silas.
 * Date: 2016/10/2
 * Time: 0:20
 */
@Component
public class SecurityFilter extends HttpServlet implements Filter {
    private static final long serialVersionUID = 1L;
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IAuthorityProvider iAuthorityProvider;

    @Value("${cas.url}")
    private String casUrl;

    @Value("${app.url}")
    private String appUrl;

    @Value("${environment}")
    private String env;

    private static Set<String> ignoreUri = new HashSet<>();

    static {
        ignoreUri.add("/test");
        ignoreUri.add("/mobile");
        ignoreUri.add("/resources/");
        ignoreUri.add("/feedback/");
        ignoreUri.add("/datav");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("SecurityFilter init");

    }

    private String getCookieValue(HttpServletRequest request, String name) {
        String value = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0)
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                    break;
                }
            }

//        logger.info("  getCookieValue  name:" + name + " value:" + value);
        return value;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

//        logger.info("SecurityFilter check");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();


        //获取访问地址的完整路径
        String url = request.getRequestURL().toString();
        if (env.equals("production")) {
            if (url.contains("10.116.17.")) {
                casUrl = "http://10.116.17.86:9001/";
                appUrl = "http://10.116.17.86:9002/";
            } else {
                casUrl = "http://30.100.153.86:9001/";
                appUrl = "http://30.100.153.86:9002/";
            }

        }

        if (env.equals("pro-dev")) {
            if (url.contains("10.116.17.")) {
                casUrl = "http://10.116.17.82:9001/";
                appUrl = "http://10.116.17.82:9002/";
            } else {
                casUrl = "http://30.100.153.82:9001/";
                appUrl = "http://30.100.153.82:9002/";
            }

        }

//        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();


//        logger.info("\n\n");
//
//        logger.info("[env] " + env + " [url]: " + request.getRequestURI() + " [session.getId] " + session.getId());
        String JSESSIONID = session.getId(); //getCookieValue(request, "JSESSIONID");

        /*if (getCookieValue(request, "token1").equals("")) {
            token = UUID.randomUUID().toString();

            Cookie cookie = new Cookie("token1", token);
            cookie.setPath("/");
            response.addCookie(cookie);

            logger.info("写入[cookie token1] " + token);
        }*/
        getCookieValue(request, "username");


        String token = "";

        boolean needCheck = true;
        for (String uri : ignoreUri) {
            if (request.getRequestURI().contains(uri)) {
                needCheck = false;
            }
        }

        logger.info("request.getRequestURI():" + request.getRequestURI() + "request.getQueryString():" + request.getQueryString() + " needCheck:" + needCheck);

        if (needCheck) {

            //if (session.getAttribute("JSS_" + JSESSIONID) == null) {
            token = request.getParameter("token");
            logger.info("first:" + session.getAttribute("first") + ",token:" + (token != null ? token : "") + ",JSESSIONID:" + (JSESSIONID != null ? JSESSIONID : ""));

            if (token != null && !token.equals("")) {

                //校验token
                if (iAuthorityProvider.registClient(token, JSESSIONID) == null) {
                    //token校验不通过，跳转到登录页
                    response.sendRedirect(casUrl + "?service=" + appUrl);
                    return;
                }
                session.setAttribute("first", false);
            }

            ResponseDTO<UserCacheDTO> responseDTO = iAuthorityProvider.authentication(JSESSIONID);

//                logger.info("iAuthorityProvider.authentication(token): " + "check JSESSIONID: " + JSESSIONID + " result:" + responseDTO.getData());

            if (responseDTO.getData() == null) {
                if (request.getRequestURI().equals("/") || request.getRequestURI().equals("/index")) {
                    response.sendRedirect(casUrl + "?service=" + appUrl);
                } else {
                    request.setCharacterEncoding("utf-8");
                    response.setCharacterEncoding("utf-8");
                    response.setStatus(200);
                    String result = "";
                    ResponseJsonBean responseBase = new ResponseJsonBean();
                    responseBase.setStatus(-1);
                    responseBase.setMsg("登录失效");
                    responseBase.setData(casUrl + "?service=" + appUrl);
                    result = JSONObject.fromObject(responseBase).toString();
                    response.getWriter().print(result);

                }
                return;
            } else {
                //对UserCacheDTO进行本地缓存
                UserUtils.setUser(responseDTO.getData());
            }
        }


        filterChain.doFilter(servletRequest, servletResponse);

    }
}
